package com.castle.fortress.admin.dify.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.lang.generator.UUIDGenerator;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.castle.fortress.admin.contract.info.entity.ContractEntity;
import com.castle.fortress.admin.contract.info.service.ContractService;
import com.castle.fortress.admin.contract.review.service.ContractReviewService;
import com.castle.fortress.admin.dify.model.*;
import com.castle.fortress.admin.dify.service.ContractReviewInfoService;
import com.castle.fortress.admin.dify.service.ContractReviewResultService;
import com.castle.fortress.admin.dify.service.FileUploadService;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.utils.ConvertUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.utils.UuidUtils;
import org.aspectj.weaver.MemberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor
public class FileUploadController {

    private final FileUploadService fileUploadService;

    @Autowired
    private ContractReviewService contractReviewService;

    @Autowired
    private ContractReviewInfoService contractReviewInfoService;

    private final ContractService contractService;

    @Autowired
    private ContractReviewResultService contractReviewResultService;

    @PostMapping("/upload")
    public RespBody<FileUploadResponse> uploadFile(@RequestBody FileUploadRequest fileUploadRequest) {

        FileUploadResponse result = fileUploadService.uploadFile(null, fileUploadRequest.getUserId(),fileUploadRequest.getFileUrl());

        return RespBody.data(result);
    }



    @PostMapping("/analyzeContractInfo")
    public ContractAnalysisResult analyzeContractInfo(@RequestParam("fileUrl") String fileUrl,
                                         @RequestParam("userId") String userId) {



        ContractAnalysisResult result = fileUploadService.analyzeContractInfo(fileUrl, userId);
        return result;
    }


    /**
     * 合同审查
     * @param request
     * @return
     */

    @PostMapping("/checkContract")
    public Object checkContract(@RequestBody ContractReviewRequest request ) {

        String responseMode =  request.getResponseMode()!=null?request.getResponseMode():"blocking";
        request.setResponseMode(responseMode);
        if(responseMode.equals("streaming")){

            SseEmitter sseEmitter = fileUploadService.reviewContract(request);
            return sseEmitter;

        }else{
            //审查结果保存至数据库
           Long infoID= this.saveReviewInfoResult(request);

            ReviewRulesResults result = fileUploadService.reviewContractBlocking(request,infoID);






            Map<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("data", result);
            map.put("msg", request.getStandpoint());

            //转化为json
            return  map;
            //return result;
        }


    }




    Long saveReviewInfoResult(ContractReviewRequest request ){

        ContractReviewInfo contractReviewInfo = new ContractReviewInfo();
        contractReviewInfo.setReviewInfoId(UUID.randomUUID().getMostSignificantBits());
        contractReviewInfo.setReviewStatus("reviewing");
        contractReviewInfo.setRuleId(request.getRuleId());
        contractReviewInfo.setReviewStartTime(DateUtil.today());
        contractReviewInfo.setContractId(request.getContractId());
        contractReviewInfo.setRuleId(request.getRiskId());

        contractReviewInfoService.save(contractReviewInfo);


        UpdateWrapper<ContractEntity> updateWrapper2=new UpdateWrapper();
        updateWrapper2.eq( "contract_id",request.getContractId());
        // updateWrapper.eq( "rule_id",request.getRuleId());
        updateWrapper2.set("review_status","reviewing");
        contractService.update(updateWrapper2);



        return contractReviewInfo.getReviewInfoId();
    }



} 